/*
	Copyright (C) 2013 Pontificia Universidad Catolica del Peru
	contact: http://avatar.inf.pucp.edu.pe/realidad-aumentada/
	address contact: Av. Universitaria 1801, San Miguel, Lima-Peru.
	
	This file is part of UbicAR PUCP.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with This program.  If not, see <http://www.gnu.org/licenses/>.
*/
/*
	Authors: Alvaro Roger Agüero Sánchez, Rodolfo Javier Galvez Meza
	Pontificia Universidad Catolica del Peru
	Departamento de Ingeniería
*/

package org.grupoavatar.guiaubicua.punto;

import java.util.ArrayList;
import java.util.List;

import org.grupoavatar.guiaubicua.R;
import org.grupoavatar.guiaubicua.VAR;
import org.grupoavatar.guiaubicua.VInicial;
import org.grupoavatar.guiaubicua.VMapa;
import org.grupoavatar.guiaubicua.auxiliares.Utiles;
import org.grupoavatar.guiaubicua.entidades.ARMarker;
import org.grupoavatar.guiaubicua.mix.DataView;
import org.grupoavatar.guiaubicua.mix.Marker;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout.LayoutParams;
import android.widget.TextView;

public class TabUbicacion extends MasterActivity {
	
	private GoogleMap mMap;	
	private boolean expanded;
	private int minHeight = 0;
//	private int maxHeight = 0;
	private int minWidth = 0;
	private TabUbicacion activity;
	
	private boolean medidasLeidas;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab_ubicacion);
		activity = this;
		setUpMapIfNeeded();
		expanded = false;
		medidasLeidas = false;
		btnUbicacion.setSelected(true);
		//btnUbicacion.setClickable(false);
		btnUbicacion.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				if (mMap != null) {
					LatLng posicion_punto = new LatLng(marker.getLatitude(), marker.getLongitude());				
			        CameraPosition cameraPosition = new CameraPosition.Builder()
			        .target(posicion_punto)      // Sets the center of the map to Mountain View
			        .zoom(17)                   // Sets the zoom
			        .bearing(0)                // Sets the orientation of the camera to east
			        .tilt(45)                   // Sets the tilt of the camera to 30 degrees		        
			        .build();                   // Creates a CameraPosition from the builder    
			        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
				}
			}
		});
		
		
		btnGeneral.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(TabUbicacion.this, TabGeneral.class);
				pasarDatos();
				startActivity(intent);
				overridePendingTransition(0, 0);
				finish();
				overridePendingTransition(0, 0);
			}
		});

		btnServicios.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(TabUbicacion.this, TabServicios.class);
				pasarDatos();
				startActivity(intent);
				overridePendingTransition(0, 0);
				finish();
				overridePendingTransition(0, 0);
			}
		});
		//Cabecera
//		TextView lblNombre = (TextView) findViewById(R.id.lblNombre);
//		lblNombre.setText(poi.getTitle());
//		TextView lblCategoria = (TextView) findViewById(R.id.lblCategoria);
//		lblCategoria.setText(MixContext.getDataSourceName(poi.getDatasource()));
//		
//		ImageView imageCate = (ImageView) this.findViewById(R.id.imgCategoria);
//        Bitmap bitfile_cate = ((ArpucpPOIMarker)poi).getDataSourceCircleIconRA(this.getResources());                
//        imageCate.setImageBitmap(bitfile_cate);  
		
        //Botones AR y Mapa
        //para cuando se busque solo en RA o mapa
      	marker.setActive(true);
        
      	/*
        Button btnVerEnAr = (Button) findViewById(R.id.btnAR);
		btnVerEnAr.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				verPoi("ar");
			}
		});
		*/
      	Button btnVerEnAr = (Button) findViewById(R.id.btnAR);
 		btnVerEnAr.setOnClickListener(new View.OnClickListener() {

 			@Override
 			public void onClick(View v) {
 				verPoi("ar");
 			}
			
 		});
      	

		Button btnVerEnMapa = (Button) findViewById(R.id.btnMapa);
		btnVerEnMapa.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				//verPoi("mapa");
				if (mMap != null) {
					LinearLayout linRoot = (LinearLayout) findViewById(R.id.ubicacion);
					LinearLayout lin = (LinearLayout) findViewById(R.id.mapLayout);
					LinearLayout linBotones = (LinearLayout) findViewById(R.id.layoutBotones);
					RelativeLayout rel = (RelativeLayout) findViewById(R.id.mapRelativeLayout);
					if (expanded) {
						if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
							lin.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, minHeight));
							rel.getLayoutParams().height = minHeight;
							if (!Utiles.isTablet(activity)) {
								lin.setLayoutParams(new RelativeLayout.LayoutParams(minWidth, minHeight));
							}
						} else {
							lin.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, minHeight));
						}
						expanded = false;
					} else {
						if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
							int maxHeight = linRoot.getHeight();        			
		        			lin.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,maxHeight));
		        			rel.getLayoutParams().height = maxHeight;
		        			
		        		} else {
		        			int maxHeight = linRoot.getHeight() - linBotones.getHeight();
		            		lin.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, maxHeight));
		        		}
						expanded = true;
					}
				} else {
					verPoi("mapa");
				}
			}
		});
        
		//Contenido
		
		//UBICACION
		TextView txtUbicacion = (TextView) findViewById(R.id.txtUbicacion);
		
		if (marker.getUbicacion().equalsIgnoreCase("")) {
			LinearLayout ubicacionLayout = (LinearLayout) findViewById(R.id.layout_ubicacion);
			ubicacionLayout.setVisibility(View.GONE);
		} else {
			txtUbicacion.setText(marker.getUbicacion());
		}
		
		//PISO/PISOS
		TextView lblPiso = (TextView) findViewById(R.id.lblPiso);
		TextView txtPiso = (TextView) findViewById(R.id.txtPiso);
		
		if (marker.getPiso() > 0) {
			lblPiso.setText("Piso");
			txtPiso.setText(String.valueOf(marker.getPiso()));
		} else if (marker.getPisos() > 0) {
			lblPiso.setText("Pisos");
			txtPiso.setText(String.valueOf(marker.getPisos()));
		} else {
			LinearLayout pisoLayout = (LinearLayout) findViewById(R.id.layout_piso);
			pisoLayout.setVisibility(View.GONE);
		}
		
		//HIJOS/PADRE
		LinearLayout padreHijosLayout = (LinearLayout)findViewById(R.id.layout_padreHijos);
		if (((marker.getHijos() != null) && (marker.getHijos().size() > 0))) {
			int tam = marker.getHijos().size();
			ContenidoListaPOIRow[] listapoi_data = new ContenidoListaPOIRow[tam];
			for (int i = 0; i < tam; i++) {
				listapoi_data[i] = new ContenidoListaPOIRow(
						marker.getHijos().get(i).getIcon(),
						marker.getHijos().get(i).getID(),
						marker.getHijos().get(i).getTitle());
			}
			establecerBloqueContenidoPOI(padreHijosLayout, "Lugares contenidos", listapoi_data);
		} else if (marker.getPadre() != null) {
			ContenidoListaPOIRow[] listapoi_data = new ContenidoListaPOIRow[1];
			listapoi_data[0] = new ContenidoListaPOIRow(
					marker.getPadre().getIcon(),
					marker.getPadre().getID(),
					marker.getPadre().getTitle());
			establecerBloqueContenidoPOI(padreHijosLayout, "Contenido en", listapoi_data);
		} else {
			padreHijosLayout.setVisibility(View.GONE);
		}
	}
	
	class ContenidoListaPOIRow {
		public int icon;
		public String id;
		public String title;

		public ContenidoListaPOIRow() {
			super();
		}

		public ContenidoListaPOIRow(int icon, String id, String title) {
			super();
			this.icon = icon;
			this.id = id;
			this.title = title;
		}
	}
	
	private void establecerBloqueContenidoPOI(LinearLayout layoutContenedor, String header, ContenidoListaPOIRow[] listapoi_data) { // parametro
		LayoutInflater inflater = (LayoutInflater) VInicial.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		  
		// header 
		LinearLayout linHeader = new	LinearLayout(VInicial.getContext());
		inflater.inflate(R.layout.contentpoi_header, linHeader);
		  
		TextView tvHeader = (TextView) linHeader.findViewById(R.id.txtContentHeader); tvHeader.setText(header);
		  
		layoutContenedor.addView(linHeader);
	  
		// rows 
		for (int i = 0; i < listapoi_data.length; i++) { 
			final ContenidoListaPOIRow row = listapoi_data[i];
			final LinearLayout linRow = new LinearLayout(VInicial.getContext());
			final int indice = i;
			inflater.inflate(R.layout.contentpoi_row, linRow);
		  
			ImageView imgIcon = (ImageView) linRow.findViewById(R.id.imgContentListPOI);
			imgIcon.setImageResource(row.icon);
		  
			TextView tvContenido = (TextView) linRow.findViewById(R.id.txtContentListPOI); tvContenido.setText(row.title);
		  
			linRow.setOnClickListener(new OnClickListener() {
				@Override public void onClick(View v) {
					if (marker.getHijos() != null && marker.getHijos().size() > 0) {
						if (bpoi.size() > 1 && poiHijoAnterior == marker.getHijos().get(indice)) {
							if (!bpoi.isEmpty())
								bpoi.remove(bpoi.size()-1);
							finish();
						} else {
							//MasterActivity.addPoi(poi.getHijos().get(indice));
							_poi = marker.getHijos().get(indice);
							addPoi(_poi);
							_bpoi = bpoi;
							_markerListTemporal = markerListTemporal;
							_poiHijoAnterior = poiHijoAnterior;
							startActivity(new Intent(VInicial.getContext(), TabGeneral.class));
						}
					}
					else if (marker.getPadre() != null) {
						if (bpoi.size() > 1) {
							if (!bpoi.isEmpty())
								bpoi.remove(bpoi.size()-1);
							finish();
						} else {
							//MasterActivity.addPoi(poi.getPadre());
							_poi = marker.getPadre();
							addPoi(_poi);
							_bpoi = bpoi;
							_markerListTemporal = markerListTemporal;
							_poiHijoAnterior = poiHijoAnterior;
							startActivity(new Intent(VInicial.getContext(), TabGeneral.class));
						}
					}
					
				}
			});
			layoutContenedor.addView(linRow);
		}
	}
	
	@Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        
//        LinearLayout linBotones = (LinearLayout) findViewById(R.id.layoutBotones);
//        int temp = linBotones.getWidth();
//		temp = linBotones.getLayoutParams().width;
//		temp = 0;
    }

	private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
//            if (mMap != null) {
            	LinearLayout lin = (LinearLayout) findViewById(R.id.mapLayout);
//            	LinearLayout linRoot = (LinearLayout) findViewById(R.id.ubicacion);
//            	LinearLayout linBotones = (LinearLayout) findViewById(R.id.layoutBotones);
            	if (Utiles.isTablet(this)) {
            		if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            			RelativeLayout rel = (RelativeLayout) findViewById(R.id.mapRelativeLayout);
            			
            			minHeight = 300;
            			lin.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, minHeight));
            			rel.getLayoutParams().height = minHeight;
            		} else {
            			minHeight = 400;
	            		lin.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, minHeight));
            		}
             	} else {
             		if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
             			RelativeLayout rel = (RelativeLayout) findViewById(R.id.mapRelativeLayout);
             			minHeight = rel.getLayoutParams().height = lin.getLayoutParams().height;
             		} else {
//             			minHeight = 200;
             			minHeight = lin.getLayoutParams().height;
             			lin.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, minHeight));
             		}
            	}
            	
            if (mMap != null)	
                setUpMap();
        }
    }
	
	private void setUpMap() {
        //mMap.addMarker(new MarkerOptions().position(new LatLng(8, 79)).title("Marker"));
		//mMap.addMarker(new MarkerOptions().position(new LatLng(latitude,longitude)).title("Estás aquí"));
		LatLng posicion_punto = new LatLng(marker.getLatitude(), marker.getLongitude());
        mMap.addMarker(new MarkerOptions().position(posicion_punto).title(marker.getTitle()));
        mMap.setMyLocationEnabled(true);          
        mMap.setMapType(1);  
        
        mMap.setInfoWindowAdapter(new InfoWindowAdapter() {
        	private final View window = getLayoutInflater().inflate(R.layout.custom_window, null);
			@Override
			public View getInfoWindow(com.google.android.gms.maps.model.Marker marker) {
				// TODO Auto-generated method stub
				//EventInfo eventInfo = eventMarkerMap.get(marker);
				String title = marker.getTitle();			 
			             TextView txtTitle = ((TextView) window.findViewById(R.id.txtInfoWindowTitle));
			 
			             if (title != null) {
			 
			                 // Spannable string allows us to edit the formatting of the text.
			 
			                 SpannableString titleText = new SpannableString(title);
			 
			                 titleText.setSpan(new ForegroundColorSpan(R.color.azul_oscuro), 0, titleText.length(), 0);
			 
			                 txtTitle.setText(titleText);
			 
			             } else {
			 
			                 txtTitle.setText("");
			 
			             }
			 
			              
			             ImageView imageCate = (ImageView) window.findViewById(R.id.ivInfoWindowMain);
			             Bitmap bitfile_cate = ((ARMarker)marker).getDataSourceCircleIconRA(VInicial.getContext().getResources());                
			             imageCate.setImageBitmap(bitfile_cate);    			             
			 
			              
			 
			    return window;
			}
			
			@Override
			public View getInfoContents(com.google.android.gms.maps.model.Marker marker) {
				// TODO Auto-generated method stub
				return null;
			}
		});
        CameraPosition cameraPosition = new CameraPosition.Builder()
        .target(posicion_punto)      // Sets the center of the map to Mountain View
        .zoom(17)                   // Sets the zoom
        .bearing(0)                // Sets the orientation of the camera to east
        .tilt(45)                   // Sets the tilt of the camera to 30 degrees
        .build();                   // Creates a CameraPosition from the builder    
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    }
	
	private void verPoi(String tipo) {
		marker.setUnicoMarker(true);
		List<Marker> poiList = new ArrayList<Marker>();
		poiList.add(marker);
		
//		List<Marker> markers = VInicial.dataView.getDataHandler().getMarkerList();
		//clonación de ArrayList, reactivado en onresume
//		markerListTemporal = new ArrayList<Marker>();
//		for (int i = 0; i < markers.size(); i++)	{
//			Marker m = markers.get(i);
//			markerListTemporal.add(m);
//		}
//		markerListTemporal = markers;
		//VInicial.dataView.getDataHandler().clearMarkers();
		VInicial.dataView.getDataHandler().setMarkerList(poiList);
		
		DataView.viendoUnicoMarker = true;
		if (tipo.equals("ar"))	{
			startActivity(new Intent(VInicial.getContext(), VAR.class));
		}
		else if (tipo.equals("mapa"))	{
			startActivity(new Intent(VInicial.getContext(), VMapa.class));
		}
		
	}
	
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		// TODO Auto-generated method stub
		super.onWindowFocusChanged(hasFocus);
		//Here you can get the size!
		if (!medidasLeidas) {
			LinearLayout mapLayout = (LinearLayout) findViewById(R.id.mapLayout);
			minWidth = mapLayout.getWidth();
			if (minWidth > 0)
				medidasLeidas = true;
		}
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu); //menuDetallesCambiarVistaMapa

		if (mMap != null) {
			MenuItem item = menu.findItem(R.id.menuDetallesCambiarVistaMapa);
			item.setVisible(true);
		}
		
        return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.menuDetallesCambiarVistaMapa:
				if (mMap != null) {
					if (mMap.getMapType() == GoogleMap.MAP_TYPE_SATELLITE)
						mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
					else
						mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
				}
				break;
			default:
				super.onOptionsItemSelected(item);
		}
//		System.out.println("ITEM: <" + item + ">");
		return true;
	}
}
